package com.dmy.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * create by YCQ for 2020/1/9 13:23
 */
public class QiniuImageServerUtil {
    private static final QiniuImageServerUtil QINIU_UPLOAD_UTIL = new QiniuImageServerUtil();
    private static final String baseUrl="http://qny.dmyily2.cn/";
    // AccessKey
    private final String accessKey = "mOj8Tm4qfILim6bZxfjp-4HbAuxDFDfu1xfYa9oX";
    // SecretKey
    private final String secretKey = "atVd8UNGkGYzghcJQZ7fxHRuok5Ip8_v0ws5c4ns";

    private final String bucket = "imageserver";

    private final  UploadManager uploadManager;

    private final  Auth auth;
    private QiniuImageServerUtil(){
        Configuration cfg = new Configuration(Zone.zone0());
        uploadManager = new UploadManager(cfg);

        auth = Auth.create(accessKey, secretKey);
    }
    public static QiniuImageServerUtil getInstance(){
        return QINIU_UPLOAD_UTIL;
    }

    private ObjectMapper objectMapper =  new ObjectMapper();
    public String uploadFileWithByteArray(byte[] fileData) throws IOException {

        String uploadToken = auth.uploadToken(bucket);

        Response response = uploadManager.put(fileData, null, uploadToken);
        Map<String,String > map = new GsonBuilder().create().fromJson(response.bodyString(),Map.class);
        return (map==null||map.isEmpty())?null:baseUrl+map.get("hash");
    }

//    public static void main(String[] args) throws IOException {
//        FileInputStream fileInputStream = new FileInputStream("d:\\FLAMING MOUNTAIN.JPG");
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//           byte[] buf = new byte[2048];
//           int len=0;
//           while ((len = fileInputStream.read(buf,0,2048))!=-1){
//               byteArrayOutputStream.write(buf,0,len);
//           }
//
//        QiniuImageServerUtil instance = QiniuImageServerUtil.getInstance();
//        String s = instance.uploadFileWithByteArray(byteArrayOutputStream.toByteArray());
//        System.out.println(s);
//    }
}
